using Digitalmes.Domain.Entities.Mes.Equipments;

namespace Digitalmes.Application.Mes.Equipments.Alarms.Commands;

/// <summary>
/// 关闭警报记录。
/// </summary>
public sealed record CloseAlarmRecordCommand(long Id) : IRequest<IResult<bool>>;

internal sealed class CloseAlarmRecordCommandHandler(IRepository<EquipAlarmRecord> repo) : IRequestHandler<CloseAlarmRecordCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(CloseAlarmRecordCommand request, CancellationToken cancellationToken)
    {
        var alarmRecord = await repo.GetByIdAsync(request.Id, cancellationToken);
        if (alarmRecord == null)
        {
            return Result.Failure("未找到要更新的警报记录");
        }

        alarmRecord.Close();

        var ok = await repo.UpdateAsync(alarmRecord, m => new
        {
            m.EndTime,
            m.Status,
            m.Duration,
        }, cancellationToken);
        return Result.From(ok);
    }
}
